#include "RAT_SceneManager.h"

namespace RAT_ENGINE
{
	RAT_SceneManager::RAT_SceneManager()
	{
	}

	RAT_SceneManager::~RAT_SceneManager()
	{
	}

	void RAT_SceneManager::Init(RAT_EntityManager* argEntityManager, std::string argScenesFileURL)
	{
		entityManager = argEntityManager;

		std::ifstream scenesFile;
		scenesFile.open(argScenesFileURL);

		while (scenesFile.good())
		{
			std::string currentLine;
			std::string url;

			std::getline(scenesFile, currentLine);

			url = currentLine.substr(0);

			LoadScene(url);
		}

		scenesFile.close();
	}

	void RAT_SceneManager::CleanUp()
	{
	}

	RAT_EntityManager* RAT_SceneManager::GetEntityManager() const
	{
		return entityManager;
	}

	std::vector<RAT_Scene*> RAT_SceneManager::GetScenes() const
	{
		return scenes;
	}

	RAT_Scene* RAT_SceneManager::GetScene(int argID) const
	{
		return scenes[argID];
	}

	RAT_Scene* RAT_SceneManager::GetScene(std::string argSceneFileURL) const
	{
		int index = 0;

		while (index < scenes.size() && scenes[index]->GetURL() != argSceneFileURL)
		{
			++index;
		}

		return scenes[index];
	}

	void RAT_SceneManager::AddScene(RAT_Scene* argScene)
	{
		scenes.push_back(argScene);
	}

	void RAT_SceneManager::LoadScene(std::string argSceneFileURL)
	{
		RAT_Scene* s = new RAT_Scene();

		s->Init(scenes.size(), argSceneFileURL);

		std::ifstream sceneFile;
		sceneFile.open(argSceneFileURL);

		while (sceneFile.good())
		{
			std::string currentLine;
			std::string type;
			std::string url;

			std::getline(sceneFile, currentLine);

			type = currentLine.substr(0, currentLine.find(";"));
			url = currentLine.substr(currentLine.find(";") + 1);

			if (type == "entitycustommodel")
			{
				s->AddEntityCustomModel(entityManager->GetEntityCustomModel(url));
			}
			else
			{
				std::cout << "Failed to load: " << currentLine << std::endl;
			}
		}

		sceneFile.close();

		AddScene(s);
	}

	void RAT_SceneManager::PrintIO()
	{
		std::cout << "Scenes:" << std::endl;
		for (unsigned int i = 0; i < scenes.size(); ++i)
		{
			scenes[i]->PrintIO();
			std::cout << std::endl;
		}
	}
}